package com.chenqi.tool.retrofit

import android.util.Log
import com.chenqi.tool.common.SpUtils
import com.google.gson.Gson
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.net.ssl.X509TrustManager

/**
 * 作者: CQ
 * 日期: 2022-02-17
 * 说明:
 */
class RetrofitFactory private constructor() {
    companion object {
        val instance : RetrofitFactory by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            RetrofitFactory()
        }

        var url = ""
    }

    private var retrofit : Retrofit? = null

    init {
        onInit()
    }

    private fun onInit() {
        val gson = Gson().newBuilder()
            .setLenient()
            .serializeNulls()
            .create()
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .addInterceptor(initLogInterceptor())
            .sslSocketFactory(SSLSocketManager.getSSLSocketFactory(),SSLSocketManager.getTrustManager()[0] as X509TrustManager)
            .hostnameVerifier(SSLSocketManager.getHostnameVerifier())
            .build()

        retrofit = Retrofit.Builder()
            .baseUrl(url)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }

    fun onRefresh() {
        onInit()
    }

    fun getApi() : Api {
        return retrofit!!.create(Api::class.java)
    }

    /**
     * 具体服务实例化
     **/
    inline fun <reified T : Api> getService() : T {
        return create(T::class.java)
    }

    fun <T : Api> create(clazz : Class<T>) : T = retrofit!!.create(clazz)

    /*
  * 日志拦截器ChannelId
  * */
    private fun initLogInterceptor() : HttpLoggingInterceptor {
        val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message : String) {
                Log.i("Retrofit", message)
            }
        })

        interceptor.level = HttpLoggingInterceptor.Level.BODY

        return interceptor
    }

//    private fun headerIntercept() : Interceptor {
//        return object : Interceptor {
//            override fun intercept(chain : Interceptor.Chain) : Response {
//                val request = chain.request().newBuilder()
//                    .addHeader("Token", SpUtils.getString(Constant.APP_TOKEN))
//                    .build()
//                return chain.proceed(request)
//            }
//        }
//    }

}